package com.lin.server.impl;

import com.lin.converter.OrderMaster2OrderDTOConverter;
import com.lin.dataobject.OrderDetail;
import com.lin.dataobject.OrderMaster;
import com.lin.dataobject.ProductInfo;
import com.lin.dto.CartDTO;
import com.lin.dto.OrderDTO;
import com.lin.enums.OrderStatusEnum;
import com.lin.enums.PayStatusEnum;
import com.lin.enums.ResultEnum;
import com.lin.exception.SellException;
import com.lin.repository.OrderDetailRepository;
import com.lin.repository.OrderMasterRepository;
import com.lin.server.OrderMasterService;
import com.lin.server.ProductInfoService;
import com.lin.utils.DateUtils;
import com.lin.utils.KeyUtils;
import com.lin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/8/29.
 */
@Service
@Slf4j
public class OrderMasterServiceImpl implements OrderMasterService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId=KeyUtils.getUniqueKey();
        BigDecimal orderAmout=new BigDecimal(BigInteger.ZERO);
        //查询商品（数量，价格）
        for (OrderDetail orderDetail:orderDTO.getOrderDetailList()) {
            ProductInfo productInfo= productInfoService.findOne(orderDetail.getProductId());
            if(productInfo==null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //计算总价
            orderAmout=productInfo.getProductPrice().multiply
                    (new BigDecimal(orderDetail.getProductQuantity())).add(orderAmout);
            //订单详情入库
            orderDetail.setDetailId(KeyUtils.getUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetailRepository.save(orderDetail);

        }
        //写入订单数据库
        OrderMaster orderMaster=new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmout);
        orderMaster.setOrderStatus(OrderStatusEnum.New.getCode());
        orderMaster.setPayStatus(PayStatusEnum.Wait.getCode());
        orderMasterRepository.save(orderMaster);
        //扣库存
        List<CartDTO> cartDTOList= orderDTO.getOrderDetailList().stream().map(e->
                new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.deCreaseStock(cartDTOList);
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterRepository.findOne(orderId);
        if (orderMaster == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage=orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);
        List<OrderDTO> orderDTOList=OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
        Page<OrderDTO> orderDTOPage=new PageImpl<>(orderDTOList,pageable,orderMasterPage.getTotalElements());

        return orderDTOPage;
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderMaster orderMaster=new OrderMaster();
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.New.getCode())){
            log.error("【取消订单】订单状态不正确，order={}，orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        orderDTO.setOrderStatus(OrderStatusEnum.Cancel.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult=orderMasterRepository.save(orderMaster);
        if (updateResult==null){
            log.error("【取消订单】更新,orderMaster={}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【取消订单】订单中无商品详情,orderDTO={}",orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        //返回库存
        List<CartDTO> cartDTOList=orderDTO.getOrderDetailList().stream()
                .map(e->new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.inCreaseStock(cartDTOList);
        //如果已支付则退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.Success.getCode())){
            //TODO
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.New.getCode())){
            log.error("【完成订单】订单状态不正确，order={}，orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.Finish.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("【完结订单】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.New.getCode())) {
            log.error("【订单支付完成】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.Wait.getCode())) {
            log.error("【订单支付完成】订单支付状态不正确, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        //修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.Success.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("【订单支付完成】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderMaster> orderMasterPage= orderMasterRepository.findAll(pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        return new PageImpl<>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }

    @Override
    public Page<OrderDTO> findAll(String startTime, String endTime, String orderId, String buyerName, String buyerPhone, String payStatus, String orderStatus, Pageable pageable) {
        Page<OrderMaster> orderMasterPage= orderMasterRepository.findAll(getSpecification(startTime,endTime,orderId,buyerName,buyerPhone,payStatus,orderStatus),pageable);
        List<OrderDTO> orderDTOS=OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
        return new PageImpl<OrderDTO>(orderDTOS,pageable,orderMasterPage.getTotalElements());
    }

    @Override
    public List<OrderDTO> findAll(String startTime, String endTime, String orderId, String buyerName, String buyerPhone, String payStatus, String orderStatus) {
        List<OrderMaster> orderMasterList= orderMasterRepository.findAll(getSpecification(startTime,endTime,orderId,buyerName,buyerPhone,payStatus,orderStatus));
        List<OrderDTO> orderDTOS=OrderMaster2OrderDTOConverter.convert(orderMasterList);
        return orderDTOS;
    }

    @Override
    public Long getSize(String startTime, String endTime, String orderId, String buyerName, String buyerPhone, String payStatus, String orderStatus) {
        return orderMasterRepository.count(getSpecification(startTime,endTime,orderId,buyerName,buyerPhone,payStatus,orderStatus));
    }

    private Specification<OrderMaster> getSpecification(String startTime, String endTime, String orderId,
                                                     String buyerName, String buyerPhone, String payStatus, String orderStatus){
        return new Specification<OrderMaster>() {
            @Override
            public Predicate toPredicate(Root<OrderMaster> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotEmpty(orderId)) {
                    predicates.add(criteriaBuilder.like(root.get("orderId"), "%" + orderId + "%"));
                }
                if (StringUtils.isNotEmpty(buyerName)){
                    predicates.add(criteriaBuilder.like(root.get("buyerName"), "%" + buyerName + "%"));
                }
                if (StringUtils.isNotEmpty(buyerPhone)){
                    predicates.add(criteriaBuilder.like(root.get("buyerPhone"), "%" + buyerPhone + "%"));
                }
                if (StringUtils.isNotEmpty(startTime)){
                    Date start= DateUtils.stringToDate(startTime);
                    predicates.add(criteriaBuilder.greaterThan(root.get("createTime"),start));
                }
                if (StringUtils.isNotEmpty(endTime)){
                    Date end=DateUtils.addDay(endTime,1);
                    predicates.add(criteriaBuilder.lessThan(root.get("createTime"),end));
                }
                if (StringUtils.isNotEmpty(payStatus)) {
                    Integer aPayStatus = Integer.valueOf(payStatus);
                    if (aPayStatus!=-1){
                        predicates.add(criteriaBuilder.equal(root.get("payStatus"),aPayStatus));
                    }
                }
                if (StringUtils.isNotEmpty(orderStatus)) {
                    Integer aOrderStatus = Integer.valueOf(orderStatus);
                    if (aOrderStatus != -1) {
                        predicates.add(criteriaBuilder.equal(root.get("orderStatus"), aOrderStatus));
                    }
                }
                return criteriaQuery.where(predicates.toArray(
                        new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
